import React, { useState } from "react";
import Menu from "rc-menu";
import { Checked, Searchfor } from "@ct0/icons";
import { createUseStyles } from "react-jss";

interface Props {
  onChange: (value?: string[]) => void;
  value?: string[];
  placeholder?: string;
}

export default TagChoice;

function TagChoice({ onChange, value: propsValue, placeholder }: Props) {
  const classes = useStyles();
  const [value, setValue] = useState<string | undefined>(undefined);

  const handleInputChange = (e: any) => {
    setValue(e.target.value.trim());
  };

  const handlePressEnter = (e: any) => {
    if (e.key !== "Enter" || !value) {
      return;
    }
    if (!propsValue?.includes(value)) {
      onChange([...(propsValue ?? []), value]);
      setValue(undefined);
    }
  };

  const handleDeselect = (selectedInfo: any) =>
    onChange(selectedInfo.selectedKeys);

  return (
    <div className={classes.tagChoice}>
      <div className={classes.search}>
        <input
          type="text"
          placeholder={placeholder}
          onChange={handleInputChange}
          onKeyPress={handlePressEnter}
          className={classes.input}
          value={value ?? ""}
        />
        <span className={classes.searchIcon}>
          <Searchfor />
        </span>
      </div>
      {propsValue && (
        <Menu
          multiple
          selectedKeys={propsValue ?? []}
          onDeselect={handleDeselect}
          className={classes.list}
        >
          {propsValue.map((p) => {
            return (
              <Menu.Item className={classes.item} key={p}>
                <span className={classes.itemValue}>{p}</span>
                <Checked />
              </Menu.Item>
            );
          })}
        </Menu>
      )}
    </div>
  );
}

const useStyles = createUseStyles({
  tagChoice: {
    width: "224px",
  },
  search: {
    position: "relative",
    padding: "6px 12px",
  },
  input: {
    height: "24px",
    lineHeight: "24px",
    border: "rgb(217, 217, 217) solid 1px",
    borderRadius: "4px",
    color: "rgb(51, 51, 51) !important",
    display: "block",
    fontSize: "12px",
    outline: "none",
    padding: "0 10px",
    width: "100%",
    boxSizing: "border-box",
    "&::placeholder": {
      color: "#c5c5c5",
    },
  },
  searchIcon: {
    position: "absolute",
    top: "6px",
    right: "18px",
    height: "24px",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    cursor: "pointer",
  },
  list: {
    margin: 0,
    padding: 0,
  },
  item: {
    margin: 0,
    padding: "10px 16px",
    display: "flex",
    justifyContent: "space-between",
    alignItems: "center",
    background: "#F5F5F5",
    color: "#0177D7",
  },
  itemValue: {
    width: "calc(100% - 30px)",
    overflow: "hidden",
    textOverflow: "ellipsis",
    whiteSpace: "nowrap",
  },
});
